<?php
class WebServiceClient {
	protected $cfg;
	
	protected $url;
	protected $key;
	protected $version;
	protected $assoc;

	public function __construct($cfg = array()) {
		$this->setCfg($cfg);
		$this->initial();
	}

	public function invoke($function_name, $parameters, $files=array(), $options=array()) {
		$request = new HttpRequest($this->url, HttpRequest::METH_POST);
		$parameters = json_encode($parameters);
		$signature = sha1($this->key.sizeof($files).$function_name.$parameters);

		$option1 = array(
			'function_name' => $function_name,
			'parameters' => $parameters,
			'signature' => $signature,	
			'version' => $this->version
		);
		$post_fields = array_merge($option1, $options);

		$request->addPostFields($post_fields);
		foreach ($files as $k => $v) {
			$request->addPostFile($k, $v);
		}

		$request->send();
		if ($request->getResponseCode() == 200) {
			return json_decode(trim($request->getResponseBody()), $this->assoc);
		} else {
			return -1;
		}
	}
	
	protected function setCfg($cfg) {
		$this->cfg = require FRAMEWORK_WEBSERVICE_CLIENT_ROOT . 'config.php';
		
		foreach($cfg as $key => $val) {
			if(array_key_exists($key, $this->cfg)) $this->cfg[$key] = $val;
		}
	}
	
	protected function initial() {
		$this->url = $this->cfg['url'];
		$this->key = $this->cfg['key'];
		$this->version = $this->cfg['version'];
		$this->assoc = $this->cfg['assoc'];
	}
}
?>